﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Carmack
{
    /// <Summary>
    /// This class implements "Dual and Single Way" message passing system
    /// On passing a particular message, related listeners are called
    /// now these listeners may or may not listen the message, if they listen 
    /// they are passed back to the broadcaster;
    /// </Summary>
    class TheSwitchboard
    {
        public void Register( eMessages message, IListener listener )
        {
            if (m_listenerMap.ContainsKey(message))
            {
                List<IListener> tempList;
                m_listenerMap.TryGetValue( message, out tempList );
                tempList.Add(listener);
            }
            else
            {
                //Add a new Message/Listener pair
                List<IListener> tempList = new List<IListener>();
                tempList.Add( listener );
                m_listenerMap.Add( message, tempList );
            }
        }
        //Single Way Message Passing
        public void Broadcast(eMessages message, object data)
        {
            List<IListener> listeners = m_listenerMap[message];
            if (listeners != null)            
                foreach (IListener obj in listeners)                
                    obj.Listen(data);            
        }
        //Dual Way Message Passing, Listeners respond if they Listen()
        public List<IListener> BroadcastEx(eMessages message, object data)
        {
            List<IListener> listeners = m_listenerMap[message];
            List<IListener> responders = new List<IListener>();            
            if (listeners != null)
            {
                foreach (IListener obj in listeners)
                {
                    if (obj.Listen(data))
                        responders.Add(obj);
                }
            }
            return responders;
        }

        public static TheSwitchboard Instance()
        {
            if (instance == null)
                instance = new TheSwitchboard();
            return instance;
        }

        #region Private_Parts
        TheSwitchboard()
        {
            m_listenerMap = new Dictionary< eMessages, List<IListener> >();
        }
        static TheSwitchboard instance;
        public Dictionary< eMessages, List<IListener> > m_listenerMap;
#endregion
    }
}
